package com.github.hgkmail.hello.processor;

import com.github.hgkmail.hello.interceptor.PrintArgsMethodInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    public static final Logger logger = LoggerFactory.getLogger(MyBeanPostProcessor.class);

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if ("testController".equals(beanName)) {
            logger.info("bean初始化前 {}", beanName);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if ("testController".equals(beanName)) {
            logger.info("bean初始化后 {}", beanName);
        }
        if ("sysMenuDao".equals(beanName)) {
            ProxyFactory proxyFactory = new ProxyFactory();
            proxyFactory.setTarget(bean);
            proxyFactory.addAdvice(new PrintArgsMethodInterceptor()); //添加切面逻辑
            return proxyFactory.getProxy(); //用proxy替换bean
        }
        return bean;
    }
}
